package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.config.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMappper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApUserRealnameServiceImpl
        extends ServiceImpl<ApUserRealnameMappper, ApUserRealname> implements ApUserRealnameService {


    @Autowired
    ApUserMapper apUserMapper;


    /**
     * 修改认证用户的状态
     * @param dto
     * @param status 状态 2 驳回   9 通过
     * @return
     */
    @Override
    //@Transactional(rollbackFor = Exception.class)  // 按照Exception回滚
    @GlobalTransactional(rollbackFor = Exception.class) //按照Exception回滚
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        //1 参数校验
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 修改认证用户的状态
        //查询认证用户
        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname == null || apUserRealname.getUserId() == null) {
            log.error("apUserRealname is Null userRealnameId:{}", dto.getId());
            CustException.cust("当前用户非法");
        }
        if (apUserRealname.getStatus().intValue() != 1) {
            log.error("apUserRealname status is not 1:{}", apUserRealname);
            CustException.cust("当前用户不是待审核状态");
        }

        //查询apuser数据
        ApUser apUser = apUserMapper.selectOne( Wrappers.<ApUser>lambdaQuery()
                        .eq(ApUser::getId, apUserRealname.getUserId())
                        .eq(ApUser::getStatus, 0)
        );
        if (apUser == null) {
            log.error("apUser is null:{}", apUserRealname.getUserId());
            CustException.cust("当前AP用户非法");
        }
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        if (status.equals(AdminConstants.PASS_AUTH)) {

            //3 如果审核通过， 远程调用保存自媒体用户
            WmUser wmUser = createWmUser(apUser);
            if (wmUser == null) {
                log.error("save wmUser error");
                CustException.cust("保存自媒体账号失败");
            }


            //4 如果审核通过， 远程调用保存文章作者的账号
            boolean flag = createApAuthor(wmUser);
            if (!flag) {
                log.error("save ApAuthor error");
                CustException.cust("保存文章作者账号失败");
            }

            //5 如果审核通过， 修改APUser 用户的flag=1
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }
        // 模拟异常出现
//        int i = 1 / 0;

        //6 返回结果
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;


    /**
     * 远程调用：保存文章作者账号
     * @param wmUser
     * @return
     */
    private boolean createApAuthor(WmUser wmUser) {
        //1 查询
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        //2 查不到则保存
        if (apAuthor == null) {
            apAuthor = ApAuthor.builder()
                    .createdTime(new Date())
                    .name(wmUser.getName())
                    .type(2)
                    .userId(wmUser.getApUserId())
                    .wmUserId(wmUser.getId())
                    .build();
          return articleFeign.save(apAuthor);
        }

        return false;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 远程调用：保存自媒体账号
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1 查询
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());

        //2 查不到则新增
        if (wmUser == null) {
            wmUser = new WmUser();
            BeanUtils.copyProperties(apUser, wmUser);
            wmUser.setNickname(apUser.getName());
            wmUser.setStatus(9);
            wmUser.setType(0);
            wmUser.setApUserId(apUser.getId()); //****
            wmUser.setCreatedTime(new Date());
            WmUser save = wemediaFeign.save(wmUser);

            // 保存成功之后，id回填
            if (save != null && save.getId() != null) {
                return save;
            }

        }

        return null;
    }

    /**
     * 分页查询认证用户列表
     * @param dto 请求参数
     * @return
     */
    @Override
    public ResponseResult listPage(AuthDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2 构建条件，执行查询
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();

        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        IPage<ApUserRealname> ipage = new Page<>(dto.getPage(), dto.getSize());
        IPage<ApUserRealname> pageResult = page(ipage, wrapper);

        //3 返回结果
        return new PageResponseResult(dto.getPage(),
                dto.getSize(),pageResult.getTotal(), pageResult.getRecords() );
    }
}
